import {
  getErrorReportByPage,
  addErrorReport,
  updateErrorReport,
  delErrorReport,
  exportErrorReport,
  getTeamMember,
  deliverErrorReport,
  viewBaseInfo,
  downloadErrorReportFile,
  getAllErrorType,
  getAllErrorPriority,
  getWorkOrderInforList,
  addErrorReport2,
  getErrorReportMembers,
  getErrorPreviewUrl,
  exportErrorReportByHandleStatus,
  getProjectNameAndCodeSimp,
  getWorkOrderInforListByInfoId,
  getWorkOrderInforByWo,
  finishErrorReport,
} from '@/services/platform/errorReport';
import '@/pages/platform/platform.module.less';
import { Ellipsis } from '@/components/Ellipsis';
import dayjs from '@/components/dayjs';
import { PlusOutlined, DownloadOutlined, UploadOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  Button,
  Form,
  Input,
  message,
  Modal,
  Tree,
  Row,
  Col,
  Select,
  Tabs,
  Upload,
  DatePicker,
  Descriptions,
  Space,
  InputNumber,
} from 'antd';
import type { DescriptionsProps, TabsProps } from 'antd';
import { Image } from 'antd';
import { sortTran, filterTran, filterTranNew } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import { ModalForm, ProFormText } from '@ant-design/pro-components';
import type { recorderrorType } from '@/pages/platform/components/interfaceProduct';
import type { tabType } from '@/pages/platform/components/interfaceProduct';
import { justify } from '@antv/g2plot/lib/plots/sankey/sankey';
import { getErrorReportByPageAndWo } from '@/services/product/productManufactInforExecute';
import { UploadFile } from 'antd/es/upload/interface';
import ErrorReportFileInfo from '@/pages/platform/errorReportFileInfo';
import { uploadErrorReportFileInfo } from '@/services/platform/errorReportFileInfo';
const ErrorReport: React.FC<{}> = (props) => {
  const actionRef = useRef<ActionType>();
  const styleCommon = { fontSize: 16, marginBottom: 20 }; //定义一个样式
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [modalVisit2, setModalVisit2] = useState(false); // 新建和编辑提示框
  const [confirmLoading2, setConfirmLoading2] = useState(false); //编辑框的disable
  const [modalVisit3, setModalVisit3] = useState(false); // 新建和编辑提示框
  const [confirmLoading3, setConfirmLoading3] = useState(false); //编辑框的disable
  const [modalVisit4, setModalVisit4] = useState(false); //pdf预览提示框
  const [confirmLoading4, setConfirmLoading4] = useState(false); //pdf预览提示框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [errorRecord, seterrorRecord] = useState<recorderrorType>();
  const [username, setusername] = useState([]);
  const [handlingname, sethandlingname] = useState([]);
  const [theerrortype, settheerrortype] = useState([]);
  const [thepriority, setthepriority] = useState([]);
  const [tabValue, setTabValue] = useState();
  const [thewo, setthewo] = useState([]);
  const [thiswo, setthiswo] = useState([]);
  // const [theWorkNumber, settheWorkNumber] = useState([]);
  const [thiswo_id, setthiswo_id] = useState([]);
  const [file, setFile] = useState();
  const [fileList, setFileList] = useState();
  const { TextArea } = Input;
  const dateFormat = 'YYYY-MM-DD';
  const [form] = Form.useForm();
  const ref = useRef(null);
  const [descriptionItemInfo, setDescriptionItemInfo] = useState([]);
  const [errorReportMembers, setErrorReportMembers] = useState([]);
  const [tabStatus, setTabStatus] = useState('1');
  const [searchItem, setSearchItem] = useState(''); //模糊搜索
  const filteredReportMembers = errorReportMembers.filter((item) =>
    item.label.toLowerCase().includes(searchItem.toLowerCase()),
  );
  const [errorPreview, setErrorPreview] = useState(''); //存储当前图纸列表的文件预览路径
  const [errorTableList, setErrorTableList] = useState([]); //异常列表

  const [allprojectname, setallprojectname] = useState([]); //新建-项目下拉框
  const [theprojectname, settheprojectname] = useState('');
  const [handlenumber, sethandlenumber] = useState(''); //处理中
  const [number1, setnumber1] = useState(''); //待处理

  //hook钩子，渲染界面初期执行,如果是通过跳转，则弹出异常处理框
  useEffect(() => {
    // console.log('父组件传递过来的props数据：', props);
    const record = props.errorRecordInfo;
    if (record !== undefined) {
      sethandlingname(record.handlingMan);
      setModalVisit(true);
      setFormTitle('异常处理');
      changeRecordForm(record); //修改record记录格式
      seterrorRecord(record);
      form.setFieldsValue({
        operator: record.operator,
        createTime: record.createTime,
        handlingMan: record.handlingMan,
        handleStatus: record.handleStatus,
        handleDes: record.handleDes,
        handleTime: record.handleTime,
        id: record.id,
        wo: record.wo,
        fileName: record.fileName,
      });
    }
  }, []);

  // 处理中+已处理
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
      align: 'center',
      sorter: true,
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      align: 'center',
      sorter: true,
      width: 150,
      render: (text) => <>{Ellipsis(text)}</>,
      valueType: 'select',
      request: async () => {
        const getproject = await getProjectNameAndCodeSimp(null);
        const projectname: { label: any; value: any }[] = [];
        getproject.data.map((item: any, index: any) => {
          projectname.push({ label: item.projectName, value: item.projectName });
        });
        return projectname;
      },
    },
    {
      title: '工单编号',
      dataIndex: 'wo',
      align: 'center',
      sorter: true,
      /*       valueType: 'select', */
      width: 180,
      /*       fieldProps: {
        options: theWorkNumber,
      },
      renderFormItem: (_, { type, defaultRender, formItemProps, fieldProps, ...rest }, form) => {
        return (
          <Select
            placeholder="请选择工单编号"
            {...fieldProps}
            // options={theWorkNumber}
            allowClear={true}
            showSearch={true}
            filterOption={(input, option) =>
              (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
            }
          />
        );
      }, */
      render: (text) => <div>{text !== 'null' ? text : '-'}</div>,
    },
    {
      title: '异常分类',
      align: 'center',
      sorter: true,
      dataIndex: 'errorType',
      valueType: 'select',

      fieldProps: {
        options: theerrortype,
      },
      // renderFormItem: () => {
      //   return (
      //     <Select
      //       placeholder="请选择异常分类"
      //       onChange={(value, label) => {}}
      //       options={theerrortype}
      //       allowClear={true}
      //     />
      //   );
      // },
    },
    {
      title: '优先级',
      dataIndex: 'priority',
      align: 'center',
      sorter: true,
      valueType: 'select',

      fieldProps: {
        options: thepriority,
      },
      render: (text, record, _, action) => {
        return (
          <div>{record.priority == 1 ? '优先' : record.priority == 2 ? '次优先' : '一般'}</div>
        );
      },
      // renderFormItem: () => {
      //   return (
      //     <Select
      //       placeholder="请选择优先级"
      //       onChange={(value, label) => {}}
      //       options={thepriority}
      //       allowClear={true}
      //     />
      //   );
      // },
    },
    {
      title: '异常申报人',
      dataIndex: 'operator',
      align: 'center',
      sorter: true,
      search: false,
    },
    {
      title: '申报时间',
      dataIndex: 'createTime',
      align: 'center',
      sorter: true,
      width: 170,
      search: false,
    },
    {
      title: '异常处理人',
      dataIndex: 'handlingMan',
      align: 'center',
      sorter: true,
      // onChange: (e) => {
      //   setSearchTerm(e.target.value);
      // },
    },
    {
      title: '要求处理日期',
      dataIndex: 'deadLine',
      align: 'center',
      sorter: true,
      width: 120,
      search: false,
    },
    {
      title: '处理状态',
      dataIndex: 'handleStatus',
      align: 'center',
      sorter: true,
      // hideInTable: true,
      render: (text, record, _, action) => {
        return (
          <div>
            {record.handleStatus == 0 ? '待处理' : record.handleStatus == 1 ? '处理中' : '已完成'}
          </div>
        );
      },
      search: false,
    },
    {
      title: '处理时间',
      dataIndex: 'handleTime',
      align: 'center',
      width: 170,
      sorter: true,
    },
    // {
    //   title: '加工工序编号',
    //   dataIndex: 'processCode',
    // },
    // {
    //   title: '加工工序名称',
    //   dataIndex: 'processName',
    // },
    // {
    //   title: '加工顺序编号',
    //   dataIndex: 'processSequence',
    // },
    // {
    //   title: '产品/柜体编号',
    //   dataIndex: 'productCode',
    // },
    // {
    //   title: '异常推送状态',
    //   dataIndex: 'pushStatus',
    // },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      align: 'center',
      hideInTable: props.projectCode === undefined ? false : true, //如果在项目信息中打开，则隐藏操作栏
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={async () => {
            sethandlingname(record.handlingMan);
            setModalVisit(true);
            setFormTitle('异常处理');
            changeRecordForm(record); //修改record记录格式
            seterrorRecord(record);
            form.setFieldsValue({
              operator: record.operator,
              createTime: record.createTime,
              handlingMan: record.handlingMan,
              handleStatus: record.handleStatus,
              handleDes: record.handleDes,
              handleTime: record.handleTime,
              id: record.id,
              wo: record.wo,
              fileName: record.fileName,
            });
          }}
        >
          异常详情
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '完成',
              content: '确定要完成吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await finishErrorReport({ id: record.id });
                actionRef.current!.reload();
              },
            });
          }}
          hidden={username != record?.operator || record.handleStatus == 2}
        >
          完成
        </a>,
      ],
    },
  ];

  // 待处理
  const columns1: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
      align: 'center',
      sorter: true,
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      align: 'center',
      sorter: true,
      width: 150,
      render: (text) => <>{Ellipsis(text)}</>,
      valueType: 'select',
      request: async () => {
        const getproject = await getProjectNameAndCodeSimp(null);
        const projectname: { label: any; value: any }[] = [];
        getproject.data.map((item: any, index: any) => {
          projectname.push({ label: item.projectName, value: item.projectName });
        });
        return projectname;
      },
    },
    {
      title: '工单编号',
      dataIndex: 'wo',
      align: 'center',
      sorter: true,

      /*       valueType: 'select', */
      width: 180,
      /*       fieldProps: {
        options: theWorkNumber,
      },
      renderFormItem: (_, { type, defaultRender, formItemProps, fieldProps, ...rest }, form) => {
        return (
          <Select
            placeholder="请选择工单编号"
            {...fieldProps}
            // options={theWorkNumber}
            allowClear={true}
            showSearch={true}
            filterOption={(input, option) =>
              (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
            }
          />
        );
      }, */
      render: (text) => <div>{text !== 'null' ? text : '-'}</div>,
    },
    {
      title: '异常分类',
      align: 'center',
      sorter: true,
      dataIndex: 'errorType',
      valueType: 'select',

      fieldProps: {
        options: theerrortype,
      },
      // renderFormItem: () => {
      //   return (
      //     <Select
      //       placeholder="请选择异常分类"
      //       onChange={(value, label) => {}}
      //       options={theerrortype}
      //       allowClear={true}
      //     />
      //   );
      // },
    },
    {
      title: '优先级',
      dataIndex: 'priority',
      align: 'center',
      sorter: true,
      valueType: 'select',
      width: 80,

      fieldProps: {
        options: thepriority,
      },
      render: (text, record, _, action) => {
        return (
          <div>{record.priority == 1 ? '优先' : record.priority == 2 ? '次优先' : '一般'}</div>
        );
      },
      // renderFormItem: () => {
      //   return (
      //     <Select
      //       placeholder="请选择优先级"
      //       onChange={(value, label) => {}}
      //       options={thepriority}
      //       allowClear={true}
      //     />
      //   );
      // },
    },
    {
      title: '异常申报人',
      dataIndex: 'operator',
      align: 'center',
      sorter: true,
      search: false,
    },
    {
      title: '申报时间',
      dataIndex: 'createTime',
      align: 'center',
      sorter: true,
      width: 200,
      search: false,
    },
    {
      title: '异常处理人',
      dataIndex: 'handlingMan',
      align: 'center',
      sorter: true,
      // onChange: (e) => {
      //   setSearchTerm(e.target.value);
      // },
    },
    {
      title: '要求处理日期',
      dataIndex: 'deadLine',
      align: 'center',
      sorter: true,
      width: 120,
      search: false,
    },
    // {
    //   title: '处理状态',
    //   dataIndex: 'handleStatus',
    //  align: 'center',sorter: true,
    //   // hideInTable: true,
    //   render: (text, record, _, action) => {
    //     return (
    //       <div>
    //         {record.handleStatus == 0 ? '待处理' : record.handleStatus == 1 ? '处理中' : '已完成'}
    //       </div>
    //     );
    //   },
    //   search: false,
    // },
    // {
    //   title: '处理时间',
    //   dataIndex: 'handleTime',
    // },
    // {
    //   title: '加工工序编号',
    //   dataIndex: 'processCode',
    // },
    // {
    //   title: '加工工序名称',
    //   dataIndex: 'processName',
    // },
    // {
    //   title: '加工顺序编号',
    //   dataIndex: 'processSequence',
    // },
    // {
    //   title: '产品/柜体编号',
    //   dataIndex: 'productCode',
    // },
    // {
    //   title: '异常推送状态',
    //   dataIndex: 'pushStatus',
    // },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      align: 'center',
      hideInTable: props.projectCode === undefined ? false : true, //如果在项目信息中打开，则隐藏操作栏
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={async () => {
            sethandlingname(record.handlingMan);
            setModalVisit(true);
            setFormTitle('异常处理');
            changeRecordForm(record); //修改record记录格式
            seterrorRecord(record);
            form.setFieldsValue({
              operator: record.operator,
              createTime: record.createTime,
              handlingMan: record.handlingMan,
              handleStatus: record.handleStatus,
              handleDes: record.handleDes,
              handleTime: record.handleTime,
              id: record.id,
              wo: record.wo,
              fileName: record.fileName,
            });
          }}
        >
          异常详情
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '完成',
              content: '确定要完成吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                if (record.handleDes != null) {
                  await delErrorReport({ id: record.id });
                  actionRef.current!.reload();
                } else {
                  message.error('处理描述为空，无法完成');
                }
              },
            });
          }}
          hidden={username != record?.operator}
        >
          完成
        </a>,
      ],
    },
  ];
  const errorDetailTabList: tabType[] = [
    {
      name: 'tab1',
      label: '异常详情',
      content: (
        <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
          <Descriptions title="" bordered column={2}>
            <Descriptions.Item label="异常分类">
              {errorRecord?.errorType ? errorRecord?.errorType : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="要求处理时间">
              {errorRecord?.deadLine ? errorRecord?.deadLine : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="处理人">
              {errorRecord?.handlingMan ? errorRecord?.handlingMan : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="发布人">
              {errorRecord?.operator ? errorRecord?.operator : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="项目名称">
              {errorRecord?.projectName ? errorRecord?.projectName : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="工单编号">
              {errorRecord?.wo ? errorRecord?.wo : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="工时">
              {errorRecord?.workHour ? errorRecord?.workHour : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="优先级">
              {errorRecord?.priority == 1 ? '优先' : errorRecord?.priority == 2 ? '次优先' : '一般'}
            </Descriptions.Item>
            <Descriptions.Item label="异常描述" span={2} contentStyle={{ height: 150 }}>
              {errorRecord?.errorDes ? errorRecord?.errorDes : '-'}
            </Descriptions.Item>
            {/* <Descriptions.Item label="异常附件" span={2}>
              <Row align={'middle'}>
                <Col span={12}>{errorRecord?.fileName ? errorRecord?.fileName : '-'}</Col>
                <Col span={12}>
                  <Button
                    key="download_button"
                    icon={<DownloadOutlined />}
                    disabled={errorRecord?.fileName == null || errorRecord?.fileName == ''}
                    onClick={async () => {
                      console.log('文件名称：', errorRecord?.fileName);
                      const URl = await getErrorPreviewUrl(errorRecord);
                      if (errorRecord?.fileName.includes('.pdf')) {
                        //如果是pdf格式，则实现预览，如果不是，则下载
                        //setModalVisit4(true);
                        setConfirmLoading4(true);
                        console.log('获取pdf文件路径：', URl.message);
                        //setErrorPreview(URl.message);
                        window.open(URl.message);
                      } else {
                        window.open(URl.message);
                      }
                      // window.open(URl.message);
                      // downloadErrorReportFile({ errorReportId: errorRecord?.id }).then((res) => {
                      //   const aLink = document.createElement('a');
                      //   document.body.appendChild(aLink);
                      //   aLink.style.display = 'none';
                      //   aLink.href = window.URL.createObjectURL(res);
                      //   aLink.setAttribute('download', `${errorRecord?.fileName}`);
                      //   aLink.click();
                      //   document.body.removeChild(aLink);
                      // });
                    }}
                    type="primary"
                  >
                    预览下载
                  </Button>
                </Col>
              </Row>
            </Descriptions.Item> */}
            <Descriptions.Item label="处理描述" span={2} contentStyle={{ height: 150 }}>
              {errorRecord?.handleDes ? errorRecord?.handleDes : '-'}
            </Descriptions.Item>
          </Descriptions>
          <Row align={'middle'} gutter={[50, 0]}>
            <Col span={12}>
              <div style={{ textAlign: 'center' }}>
                <Button
                  type="primary"
                  disabled={
                    errorRecord?.handleStatus == '1' ||
                    username != handlingname ||
                    errorRecord?.handleStatus == '2'
                  }
                  onClick={() => {
                    setModalVisit2(true);
                  }}
                >
                  去处理
                </Button>
              </div>
            </Col>
            <Col span={12}>
              <div style={{ textAlign: 'center' }}>
                <Button
                  type="primary"
                  disabled={errorRecord?.handleStatus == 2 || username != errorRecord?.operator}
                  onClick={async () => {
                    if (errorRecord?.errorDes == undefined || errorRecord?.errorDes == null) {
                      message.error('异常描述为空，不允许完成异常');
                    } else if (
                      errorRecord?.handleDes === null ||
                      errorRecord?.handleDes === undefined
                    ) {
                      message.error('处理描述为空，不允许完成异常');
                    } else {
                      errorRecord.handleStatus = '2';
                      // console.log(errorRecord);
                      const errorReportDto = errorRecord;
                      const result = await updateErrorReport(errorReportDto);
                      // console.log(result, '结果');
                      if (result != null) {
                        message.success('异常已完成');
                        setModalVisit(false);
                        actionRef.current?.reload();
                      }
                    }
                  }}
                >
                  完成
                </Button>
              </div>
            </Col>
          </Row>
        </Space>
      ),
    },
    {
      name: 'tab2',
      label: '异常附件',
      content: <ErrorReportFileInfo errorRecord={errorRecord}></ErrorReportFileInfo>,
    },
  ];

  //获取：用户名（填报人）
  const getuser = async () => {
    const getuserlist = await viewBaseInfo(null);
    setusername(getuserlist.data.name);
  };

  //获取异常处理人
  const getErrorReportMembersInfo = async () => {
    const errorReportMembersArray = await getErrorReportMembers(null);
    setErrorReportMembers(
      errorReportMembersArray.data?.map((item) => {
        return { value: item.name, label: item.name };
      }),
    );
    // console.log('异常处理人列表：', errorReportMembers);
  };

  //修改记录文件格式
  const changeRecordForm = (value) => {
    // console.log('异常处理数据', value);
    const descriptionItem = [];
    let index = 1;
    for (const item in value) {
      descriptionItem.push({ key: index++, label: item, children: value[item] });
    }
    setDescriptionItemInfo(descriptionItem);
    console.log('重构后的数组', descriptionItemInfo);
  };

  //去处理
  const dealwith = async () => {
    form
      .validateFields()
      .then(async () => {
        const res = { ...form.getFieldsValue() };
        errorRecord.handleDes = res.handleDes;
        const errorReportDto = errorRecord;
        errorReportDto.handleStatus = '1';
        const currentTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss');
        errorReportDto.handleTime = currentTime;
        console.log(currentTime);

        const formData = new FormData();
        res?.file?.fileList.map((file: any) => {
          formData.append('file', file.originFileObj);
        });
        console.log(errorReportDto);
        const fileParams = { errorReportId: errorReportDto?.id, file: formData };
        //附件上传
        const fileUploadResult = await uploadErrorReportFileInfo(fileParams);
        //异常处理结果
        const result = await updateErrorReport(errorReportDto);
        // console.log('结果', result);
        if (result && fileUploadResult) {
          message.success('处理成功！');
          form.resetFields();
        }
        setConfirmLoading2(false);
        setModalVisit2(false);
        actionRef.current?.reload();
      })
      .catch(() => {
        setConfirmLoading2(false);
      });
  };

  //新增异常
  const add_error = async () => {
    setConfirmLoading3(true);
    form
      .validateFields()
      .then(async () => {
        const res = form.getFieldsValue();
        console.log('res', res);
        const formData = new window.FormData();
        // console.log('文件列表', fileList);
        fileList?.map((item: any) => {
          formData.append('file', item.originFileObj); //需要将file类型的文件转入formData中，不然后端接收不到
        });
        res.file = formData;
        res.deadLine = dayjs(res.deadLinetime).format(dateFormat);
        res.operator = username;
        res.Wo = thiswo;
        res.workOrderInforId = thiswo_id;
        res.projectName = theprojectname;
        console.log('新增异常信息：', res);
        const result = await addErrorReport2(res);
        if (result != null) {
          message.success('异常新增成功');
        }
        setModalVisit3(false);
        form.resetFields();
        actionRef.current!.reload();
      })
      .catch(() => {
        setModalVisit3(false);
        form.resetFields();
      });
  };

  const onFilesChange = (info: any) => {
    console.log(info);
    setFileList(info.fileList);
  };

  /* 在文件上传之前进行检验 */
  const handleBeforeUpload = (info: any) => {
    // console.log('在文件上传之前进行检验', info);
    //检验文件大小
    // if (info.size) {
    //   const isLt = info.size / 1024 / 1024 < 1000;
    //   if (!isLt) {
    //     alert(`上传文件大小不能超过 ${1} GB!`);
    //     return false;
    //   } else {
    //     //验证通过
    //   }
    // }
    //检验成功
    return false; //这里必须要返回false，来阻止原生的组件的默认action行为，不然会显示存储错误的信息
  };

  const handleSubmit = () => {
    setModalVisit(false);
    actionRef.current!.reload();
  };

  // 获取下拉框内容
  const getselect = async () => {
    // 异常类型
    const geterrortype = await getAllErrorType(null);
    const errortypeOptionContract = [];
    geterrortype.data.map((item: any, index: any) => {
      errortypeOptionContract.push({ value: item.errorType, label: item.errorType });
    });
    settheerrortype(errortypeOptionContract);
    // 异常优先级
    const getpriority = await getAllErrorPriority(null);
    const priorityOptionContract = [];
    getpriority.data.map((item: any, index: any) => {
      priorityOptionContract.push({ value: item.priority, label: item.priorityDes });
    });
    setthepriority(priorityOptionContract);
    // 工单列表
    const getwo = await getWorkOrderInforList(null);
    const woContract = [];
    getwo.data.map((item: any, index: any) => {
      woContract.push({ value: item.id, label: item.wo });
    });
    setthewo(woContract);
    // const woContract1 = [];
    // getwo.data.map((item: any, index: any) => {
    //   woContract1.push({ value: item.wo, label: item.wo });
    // });
    // settheWorkNumber(woContract1);
    // console.log(theWorkNumber);
    // 项目列表
    const getproject = await getProjectNameAndCodeSimp(null);
    const projectContract = [];
    getproject.data.map((item: any, index: any) => {
      projectContract.push({ value: item.infoId, label: item.projectName });
    });
    setallprojectname(projectContract);
  };

  // 获取下拉框wo和woid的值
  const getwoandid = async (value: any) => {
    console.log('下拉框信息', value);
    if (value !== undefined) {
      setthiswo(value.label);
      setthiswo_id(value.value);
    }
    const result = await getWorkOrderInforByWo({ wo: value.label });
    const projectName = result?.data?.projectName;
    console.log(props.projectInfo, projectName);
    if (projectName && !props.projectInfo) {
      form.setFieldsValue({ projectName: projectName });
    }
  };

  //定义Tabs的子结构的数组
  const tabList: tabType[] = [
    {
      name: 'tab1',
      label: '待处理',
      content: (
        <>
          <ProTable
            headerTitle="异常处理查询"
            actionRef={actionRef} //用于触发刷新操作等，看api
            rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
            formRef={ref}
            search={
              props.projectCode === undefined
                ? {
                    labelWidth: 100,
                    defaultCollapsed: true,
                  }
                : false //如果是在项目信息中打开，则隐藏搜索栏
            }
            toolBarRender={(action, { selectedRows }) => [
              props.projectCode === undefined ? (
                <Button
                  key="button"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    console.log('--props--', props);
                    const { projectInfo } = props;
                    if (projectInfo) {
                      form.setFieldValue('projectName', projectInfo.projectName);
                      settheprojectname(projectInfo.projectName);
                    } else {
                      form.resetFields();
                    }
                    setConfirmLoading3(false);
                    setModalVisit3(true);
                  }}
                  type="primary"
                  hidden={props.errorRecordInfo != undefined}
                >
                  新建
                </Button>
              ) : (
                <></>
              ), //如果是项目信息中打开，则隐藏新建按钮
              <Button
                key="exportbutton1"
                icon={<PlusOutlined />}
                onClick={() => {
                  exportErrorReport({}).then((res) => {
                    const aLink = document.createElement('a');
                    document.body.appendChild(aLink);
                    aLink.style.display = 'none';
                    aLink.href = window.URL.createObjectURL(res);
                    aLink.setAttribute('download', `ErrorReport.xls`);
                    aLink.click();
                    document.body.removeChild(aLink);
                  });
                }}
                type="primary"
              >
                导出
              </Button>,
            ]}
            request={async (params = {}, sort, filter) => {
              const res = { ...params, handleStatus: 0 };
              const sorters = sortTran(sort);
              const filters = filterTranNew(res);
              const res_ = { handleStatus: 0 }; //当前页的数量
              const filters_ = filterTranNew(res_); //当前页的数量
              const res2 = { handleStatus: 1 }; //用于获取处理中的异常数量
              const filters2 = filterTranNew(res2); //用于获取处理中的异常数量
              if (props.projectName) {
                const filters1 = {
                  andOr: 'and',
                  field: 'projectName',
                  operator: 'like',
                  value: props.projectName,
                };
                filters.push(filters1);
                filters_.push(filters1);
                filters2.push(filters1);
              }
              if (props.projectCode != undefined) {
                const filters1 = {
                  andOr: 'and',
                  field: 'wo',
                  operator: 'like',
                  value: props.projectCode,
                };
                filters.push(filters1);
                filters_.push(filters1);
                filters2.push(filters1);
              }
              // result:当前页面结果，result_nofilter：当前页面数据数量，result2：处理中数量
              const [result, result_nofilter, result2] = await Promise.all([
                getErrorReportByPage({
                  ...params,
                  sorters: sorters,
                  filters: filters,
                }),
                getErrorReportByPage({
                  ...params,
                  sorters: sorters,
                  filters: filters_,
                }),
                getErrorReportByPage({
                  ...params,
                  sorters: sorters,
                  filters: filters2,
                })
              ]);
              setnumber1(result_nofilter.data.totalElements);//待处理数量
              sethandlenumber(result2.data.totalElements);//处理中数量
              getErrorReportMembersInfo();
              getuser();
              getselect();
              if (props.errorRecordInfo != undefined) {
                const errorParams = {
                  wo: props.workOrderInforCode,
                  pageEntity: {
                    current: 1,
                    filters: [],
                    pageSize: 6,
                    sorters: [],
                  },
                };
                const ErrotList = await getErrorReportByPageAndWo(errorParams);
                // console.log('异常列表：', ErrotList);
                const errorTableList = []; //进行数据过滤
                ErrotList.data.content.map((item) => {
                  if (item.handleStatus == '0') {
                    errorTableList.push(item);
                  }
                });
                console.log('重构数组:', errorTableList);
                return {
                  data: errorTableList,
                };
              } else {
                return {
                  data: result.data.content,
                  total: result.data.totalElements,
                  success: result.success,
                };
              }
            }}
            columns={columns1}
            scroll={{ x: 1300, y: 350 }}
            height="100%"
            rowSelection={{}}
          />
        </>
      ),
    },
    {
      name: 'tab2',
      label: '处理中',
      content: (
        <div>
          <ProTable
            headerTitle="异常处理查询"
            actionRef={actionRef} //用于触发刷新操作等，看api
            rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
            formRef={ref}
            search={
              props.projectCode === undefined
                ? {
                    labelWidth: 100,
                    defaultCollapsed: true,
                  }
                : false //如果是在项目信息中打开，则隐藏搜索栏
            }
            toolBarRender={(action, { selectedRows }) => [
              // <Button
              //   key="button"
              //   icon={<PlusOutlined />}
              //   onClick={() => {
              //     form.resetFields();
              //     setModalVisit3(true);
              //   }}
              //   type="primary"
              // >
              //   新建
              // </Button>,
              <Button
                key="exportbutton2"
                icon={<PlusOutlined />}
                onClick={() => {
                  exportErrorReport({}).then((res) => {
                    const aLink = document.createElement('a');
                    document.body.appendChild(aLink);
                    aLink.style.display = 'none';
                    aLink.href = window.URL.createObjectURL(res);
                    aLink.setAttribute('download', `ErrorReport.xls`);
                    aLink.click();
                    document.body.removeChild(aLink);
                  });
                }}
                type="primary"
              >
                导出
              </Button>,
            ]}
            request={async (params = {}, sort, filter) => {
              const res = { ...params, handleStatus: 1 };
              const sorters = sortTran(sort);
              const filters = filterTranNew(res);
              const res_ = { handleStatus: 1 }; //当前页的数量
              const filters_ = filterTranNew(res_); //当前页的数量
              if (props.projectName) {
                const filters1 = {
                  andOr: 'and',
                  field: 'projectName',
                  operator: 'like',
                  value: props.projectName,
                };
                filters.push(filters1);
                filters_.push(filters1);
              }
              if (props.projectCode != undefined) {
                const filters1 = {
                  andOr: 'and',
                  field: 'wo',
                  operator: 'like',
                  value: props.projectCode,
                };
                filters.push(filters1);
                filters_.push(filters1);
              }
              // result:当前页面结果，result_nofilter：当前页面数据数量
              const [result, result_nofilter] = await Promise.all([
                getErrorReportByPage({
                  ...params,
                  sorters: sorters,
                  filters: filters,
                }),
                getErrorReportByPage({
                  ...params,
                  sorters: sorters,
                  filters: filters_,
                }),
              ]);
              sethandlenumber(result_nofilter.data.totalElements);
              // console.log('异常处理数据：', result.data.content);
              getErrorReportMembersInfo();
              getuser();
              getselect();
              if (props.errorRecordInfo !== undefined) {
                const errorParams = {
                  wo: props.workOrderInforCode,
                  pageEntity: {
                    current: 1,
                    filters: [],
                    pageSize: 6,
                    sorters: [],
                  },
                };
                const ErrotList = await getErrorReportByPageAndWo(errorParams);
                // console.log('异常列表：', ErrotList);
                const errorTableList = []; //进行数据过滤
                ErrotList.data.content.map((item) => {
                  if (item.handleStatus == '1') {
                    errorTableList.push(item);
                  }
                });
                console.log('重构数组:', errorTableList);
                return {
                  data: errorTableList,
                };
              } else {
                return {
                  data: result.data.content,
                  total: result.data.totalElements,
                  success: result.success,
                };
              }
              // return {
              //   data: result.data.content,
              //   total: result.data.totalElements,
              //   success: result.success,
              // };
            }}
            columns={columns}
            scroll={{ x: 1800, y: 350 }}
            rowSelection={{}}
          />
        </div>
      ),
    },
    {
      name: 'tab3',
      label: '已完成',
      content: (
        <div>
          <ProTable
            headerTitle="异常处理查询"
            actionRef={actionRef} //用于触发刷新操作等，看api
            rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
            formRef={ref}
            search={
              props.projectCode === undefined
                ? {
                    labelWidth: 100,
                    defaultCollapsed: true,
                  }
                : false //如果是在项目信息中打开，则隐藏搜索栏
            }
            toolBarRender={(action, { selectedRows }) => [
              <Button
                key="exportbutton3"
                icon={<PlusOutlined />}
                onClick={() => {
                  exportErrorReport({}).then((res) => {
                    const aLink = document.createElement('a');
                    document.body.appendChild(aLink);
                    aLink.style.display = 'none';
                    aLink.href = window.URL.createObjectURL(res);
                    aLink.setAttribute('download', `ErrorReport.xls`);
                    aLink.click();
                    document.body.removeChild(aLink);
                  });
                }}
                type="primary"
              >
                导出
              </Button>,
            ]}
            request={async (params = {}, sort, filter) => {
              const res = { ...params, handleStatus: 2 };
              const sorters = sortTran(sort);
              const filters = filterTranNew(res);
              if (props.projectName) {
                const filters1 = {
                  andOr: 'and',
                  field: 'projectName',
                  operator: 'like',
                  value: props.projectName,
                };
                filters.push(filters1);
              }
              if (props.projectCode != undefined) {
                const filters1 = {
                  andOr: 'and',
                  field: 'wo',
                  operator: 'like',
                  value: props.projectCode,
                };
                filters.push(filters1);
              }
              const result = await getErrorReportByPage({
                ...params,
                sorters: sorters,
                filters: filters,
              });
              if (props.errorRecordInfo !== undefined) {
                const errorParams = {
                  wo: props.workOrderInforCode,
                  pageEntity: {
                    current: 1,
                    filters: [],
                    pageSize: 6,
                    sorters: [],
                  },
                };
                const ErrotList = await getErrorReportByPageAndWo(errorParams);
                // console.log('异常列表：', ErrotList);
                const errorTableList = []; //进行数据过滤
                ErrotList.data.content.map((item) => {
                  if (item.handleStatus == '2') {
                    errorTableList.push(item);
                  }
                });
                console.log('重构数组:', errorTableList);
                return {
                  data: errorTableList,
                };
              } else {
                return {
                  data: result.data.content,
                  total: result.data.totalElements,
                  success: result.success,
                };
              }
              // return {
              //   data: result.data.content,
              //   total: result.data.totalElements,
              //   success: result.success,
              // };
            }}
            columns={columns}
            scroll={{ x: 1600, y: 350 }}
            rowSelection={{}}
          />
        </div>
      ),
    },
  ];

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <Tabs
        type="card"
        onChange={(value) => {
          console.log('tab序列信息：', value);
        }}
        destroyInactiveTabPane={true}
        items={tabList.map((item, i) => {
          const id = String(i + 1);
          return {
            label:
              i == 0 ? (
                <div className="text">
                  {item.label}
                  <div className="point">
                    <div className="number">{number1}</div>
                  </div>
                </div>
              ) : i == 1 ? (
                <div className="text">
                  {item.label}
                  <div className="point">
                    <div className="number">{handlenumber}</div>
                  </div>
                </div>
              ) : (
                <div>{item.label}</div>
              ),
            key: id,
            children: <div>{item.content}</div>,
          };
        })}
      />
      <Modal
        visible={modalVisit}
        // title={formTitle}
        width={1500}
        // onFinish={handleSubmit}
        // modalProps={{
        //   destroyOnClose: true,
        //   onCancel: () => {
        //     setModalVisit(false);
        //     actionRef.current!.reload();
        //   },
        // }}
        onCancel={() => {
          setModalVisit(false);
          actionRef.current?.reload();
        }}
        footer={null} //取消页脚
      >
        <Tabs
          defaultActiveKey={'1'}
          style={{ backgroundColor: 'white' }}
          type="card"
          onChange={(value) => {
            console.log('tab序列信息：', value);
          }}
          destroyInactiveTabPane={true}
          items={errorDetailTabList.map((item, i) => {
            const id = String(i + 1);
            return {
              label: item.label,
              key: id,
              children: <div>{item.content}</div>,
            };
          })}
        />
      </Modal>
      <Modal
        className="errorPreviewContainer"
        visible={modalVisit4}
        title="文件预览"
        onCancel={() => {
          setModalVisit4(false);
        }}
        width={1500}
        footer={null}
      >
        <iframe className="errorPreviewStyle" src={errorPreview}></iframe>
      </Modal>
      <Modal
        title="异常处理"
        visible={modalVisit2}
        onOk={dealwith}
        confirmLoading={confirmLoading2}
        destroyOnClose
        width={680}
        onCancel={() => {
          setModalVisit2(false);
          actionRef.current?.reload();
        }}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="right"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item
            label="处理描述"
            name="handleDes"
            rules={[{ required: true, message: '请填写处理描述!' }]}
          >
            <TextArea placeholder="请填写处理描述" autoSize={{ minRows: 5, maxRows: 8 }} />
          </Form.Item>
          <Form.Item
            label="附件上传"
            name="file"
            /*             rules={[{ required: true, message: '请选择处理附件!' }]} */
          >
            <Upload
              file-list="fileList"
              onChange={onFilesChange} //通过覆盖默认的上传行为，可以自定义自己的上传实现
              showUploadList={true}
              beforeUpload={handleBeforeUpload}
              multiple
            >
              <Button className="standProduct_UploadStyle" icon={<UploadOutlined />}>
                上传文件
              </Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="新增异常"
        visible={modalVisit3}
        width={900}
        onOk={add_error}
        destroyOnClose
        confirmLoading={confirmLoading3}
        onCancel={() => setModalVisit3(false)}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="right"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item name="projectName" label="项目名称">
                <Select
                  placeholder="请选择项目名称"
                  disabled={props.projectInfo} //如果传入项目信息，则项目名称就直接默认，不可修改
                  onChange={async (value: any, option: any) => {
                    console.log('value,option:', value, option);
                    // 更新工单下拉框
                    if (value == undefined) {
                      //没有选择项目，显示全部工单编号
                      const getwo = await getWorkOrderInforList(null);
                      const woContract1: any[] = [];
                      getwo?.data.map((item: any, index: any) => {
                        woContract1.push({ value: item.id, label: item.wo });
                      });
                      setthewo(woContract1);
                    } else {
                      const getwolist = await getWorkOrderInforListByInfoId({
                        infoId: value,
                      });
                      const woContract: any[] = [];
                      getwolist?.data.map((item: any, index: any) => {
                        woContract.push({ value: item.id, label: item.wo });
                      });
                      setthewo(woContract);
                      settheprojectname(option.label); // 保存项目名称，新建用
                    }
                    form.setFieldsValue({
                      Wo: '',
                    });
                  }}
                  options={allprojectname}
                  // labelInValue
                  autoClearSearchValue={false}
                  allowClear
                  showSearch={true}
                  filterOption={(input, option) =>
                    (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                  }
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="Wo" label="工单编号">
                <Select
                  placeholder="请选择工单编号"
                  onChange={getwoandid}
                  options={thewo}
                  labelInValue
                  allowClear
                  showSearch={true}
                  filterOption={(input, option) =>
                    (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                  }
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item
                label="异常分类"
                name="errorType"
                rules={[{ required: true, message: '请选择异常分类!' }]}
              >
                <Select
                  placeholder="请选择异常分类"
                  onChange={(value) => {}}
                  options={theerrortype}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="handlingMan"
                label="异常处理人"
                rules={[{ required: true, message: '请输入异常处理人!' }]}
              >
                <Select
                  placeholder="请选择异常处理人"
                  onChange={(value) => {
                    if (value == username) {
                      message.warning('处理人和申报人不能相同');
                      form.setFieldsValue({
                        handlingMan: '',
                      });
                    }
                  }}
                  showSearch={true}
                  options={errorReportMembers}
                  filterOption={(input, option) =>
                    (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                  }
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item
                label="异常优先级"
                name="priority"
                rules={[{ required: true, message: '请选择异常优先级!' }]}
              >
                <Select
                  placeholder="请选择异常优先级"
                  onChange={(value) => {}}
                  options={thepriority}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="deadLinetime"
                label="要求处理时间"
                rules={[{ required: true, message: '请输入要求处理时间!' }]}
              >
                <DatePicker style={{ width: 290 }} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item name="workHour" label="工时(h)">
                <InputNumber
                  // style={{ width: 350 }}
                  min={0}
                  addonAfter="h"
                  step="0.01"
                  stringMode
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="异常附件" name="fileList">
                <Upload
                  file-list="fileList"
                  onChange={onFilesChange} //通过覆盖默认的上传行为，可以自定义自己的上传实现
                  showUploadList={true}
                  beforeUpload={handleBeforeUpload}
                  multiple
                >
                  <Button className="standProduct_UploadStyle" icon={<UploadOutlined />}>
                    上传文件
                  </Button>
                </Upload>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={24}>
              <Form.Item
                name="errorDes"
                label="问题描述"
                rules={[{ required: true, message: '请输入问题描述!' }]}
              >
                <TextArea rows={3} />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default ErrorReport;
